﻿
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
	GameRoot gameRoot;
	public UIManager(GameRoot gameRoot) {
		this.gameRoot = gameRoot;
	}

	public void OnInit() {
		ReadJson();
		PushStack(UIPanelType.BackGround);
	}


	Dictionary<UIPanelType, string> dicPanelType;
	public void ReadJson() {
		if (dicPanelType == null)
			dicPanelType = new Dictionary<UIPanelType, string>();
		TextAsset text = Resources.Load<TextAsset>("PanelType");
		Debug.Log(text.text);
		PanelInfos infos = JsonUtility.FromJson<PanelInfos>(text.text);
		Debug.Log(infos.panelInfos.Count);
		foreach (PanelInfo info in infos.panelInfos) {
			// Debug.Log(info.uiPanelType + " " + info.path);
			dicPanelType.Add(info.uiPanelType, info.path);
		}
		Debug.Log(dicPanelType.Count);

	}

	Dictionary<UIPanelType, BasePanel> dicBasePanel;
	public BasePanel GetPanel(UIPanelType panelType) {
		BasePanel basePanel;
		if (dicBasePanel == null) dicBasePanel = new Dictionary<UIPanelType, BasePanel>();


		//int.Parse("");
		dicBasePanel.TryGetValue(panelType, out basePanel);
		if (basePanel == null) {
			string path;
			dicPanelType.TryGetValue(panelType, out path);
			GameObject go = Object.Instantiate(Resources.Load(path)) as GameObject;
			go.transform.SetParent(GameObject.Find("Canvas").transform, false);
			dicBasePanel.Add(panelType, go.GetComponent<BasePanel>());
			basePanel = go.GetComponent<BasePanel>();
		}
		return basePanel;
	}

	Stack<BasePanel> baseStack;
	public void PushStack(UIPanelType uIPanelType) {
		if (baseStack == null) baseStack = new Stack<BasePanel>();

		if (baseStack.Count > 0) {
			baseStack.Peek().OnPause();
		}

		Debug.Log(uIPanelType);
		BasePanel basePanel = GetPanel(uIPanelType);
		// Debug.Log(basePanel);
		basePanel.OnEnter();
		baseStack.Push(basePanel);
	}

	public void PopStack() {
		if (baseStack == null) baseStack = new Stack<BasePanel>();

		if (baseStack.Count > 0) {
			baseStack.Peek().OnExit();
			baseStack.Pop();
			if (baseStack.Count > 0) {
				baseStack.Peek().OnResume();
			}
		}
	}
}
